<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { onBeforeMount, reactive, ref } from 'vue'
import apiUser from '@/api/modules/user'

function useFormDialog() {
  const dialogVisible = ref(false)
  const mode = ref<'create' | 'edit'>('create')
  const formModal = reactive<UserApiTypes>({
    id: -1,
    username: '',
    password: '',
  })
  const open = () => {
    dialogVisible.value = true
  }

  const setMode = (type: 'create' | 'edit') => {
    mode.value = type
  }
  const setForm = (source: UserApiTypes) => {
    formModal.id = source.id
    formModal.username = source.username
    formModal.password = source.password
  }
  const clearForm = () => {
    formModal.id = -1
    formModal.username = ''
    formModal.password = ''
  }

  const close = () => {
    dialogVisible.value = false
  }

  return {
    dialogVisible,
    mode,
    open,
    close,
    setMode,
    formModal,
    setForm,
    clearForm,
  }
}

const { open, close, setMode, dialogVisible, mode, formModal, setForm, clearForm } = useFormDialog()

function editUser(row: UserApiTypes) {
  setForm(cloneDeep(row))
  setMode('edit')
  open()
}

function createUser() {
  clearForm()
  setMode('create')
  open()
}

// 获取用户列表
const paginator = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const data = ref<UserApiTypes[]>([])
const loading = ref(true)
function loadAdminUsers() {
  loading.value = true
  apiUser.getList({
    page: paginator.page,
    pageSize: paginator.pageSize,
  }).then((res) => {
    data.value = res.data.list
    paginator.total = res.data.total
  }).finally(() => {
    loading.value = false
  })
}

onBeforeMount(() => {
  loadAdminUsers()
})

// 创建/编辑用户事件
function onCommitForm() {
  if (formModal.username === '') {
    ElMessage({
      type: 'error',
      message: '用户名不能为空',
    })
    return
  }
  if (formModal.password === '') {
    ElMessage({
      type: 'error',
      message: '密码不能为空',
    })
    return
  }
  close()
  loading.value = true
  const apiPromise = mode.value === 'create'
    ? apiUser.add({
      username: formModal.username,
      password: formModal.password,
    })
    : apiUser.edit(formModal)
  apiPromise.then(() => {
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
  }).finally(() => {
    loadAdminUsers()
  })
}

// 删除用户事件
function deleteUser(id: number) {
  loading.value = true
  apiUser.delete(id).then(() => {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  }).finally(() => {
    loadAdminUsers()
  })
}
</script>

<template>
  <div>
    <PageMain v-loading="loading">
      <el-button type="primary" @click="createUser">
        添加用户
      </el-button>
      <el-table :data="data" stripe>
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="editUser(row)">
              编辑
            </el-button>

            <el-popconfirm
              v-if="row.role !== 'super'"
              confirm-button-text="确认"
              cancel-button-text="取消"
              confirm-button-type="danger"
              icon-color="#F56C6C"
              title="是否删除该用户"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          v-model:current-page="paginator.page"
          v-model:page-size="paginator.pageSize"
          layout="sizes, prev, pager, next"
          :total="paginator.total"
          :page-sizes="[5, 10, 20, 50]"
          background
          @current-change="loadAdminUsers()"
          @size-change="loadAdminUsers()"
        />
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="mode === 'create' ? '添加用户' : '编辑用户'"
        width="100%" style="max-width: 600px;"
      >
        <el-form :model="formModal" label-width="60px">
          <el-row :gutter="20">
            <el-col :xs="24" :md="12">
              <el-form-item label="用户名">
                <el-input v-model="formModal.username" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="密码">
                <el-input v-model="formModal.password" placeholder="请输入密码" type="password" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="onCommitForm">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </PageMain>
  </div>
</template>

<style lang="scss" scoped>
.page {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
